/*
 * @Description:
 * @Version: 1.0
 * @Autor: gaoluo
 * @Date: 2021-11-19 17:11:29
 * @LastEditors: gaoluo
 * @LastEditTime: 2021-11-23 14:17:51
 * @FilePath: /nhw/src/utils/getPosition.js
 */
//
// import BaiduMap from "BaiduMap";

// const map = new BaiduMap.Geolocation();
// function getPosition() {
//   return new Promise((resolve, reject) => {
//     map.getCurrentPosition(
//       (position) => {
//         const { lat, lng } = position.point;
//         const { province, city, district, street, street_number } =
//           position.address;
//         const address = province + city + district + street + street_number;
//         resolve({ lat, lng, address })
//       },
//       (e) => {
//         console.log(e);
//         reject(e)
//         this.$toast("定位失败！");
//       },
//       { provider: "baidu" }
//     );
//   })
// }

// export default getPosition;


//高德地图获取位置功能

import AMapToBDMap from "@/utils/AMapToBDMap";
import AMapLoader from "@amap/amap-jsapi-loader";

const createMap = async () => {
  let geolocation = null, AMap = null;
  AMap = await AMapLoader.load({
    key: "46e1d72f2060dc375ac04f10abfd8cdb",
    version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Geolocation"]
  })
  geolocation = new AMap.Geolocation({
    enableHighAccuracy: true,//是否使用高精度定位，默认:true
    timeout: 100,          //超过10秒后停止定位，默认：无穷大
    maximumAge: 0,           //定位结果缓存0毫秒，默认：0
  })
  return { AMap, geolocation }
}

function getPosition() {
  return new Promise((resolve, reject) => {
    createMap().then(({ geolocation }) => {
      geolocation.getCurrentPosition((status, result) => {
        if (status === "complete") {
          const { position, formattedAddress } = result;
          const locaInfo = AMapToBDMap(position.lng, position.lat)
          locaInfo.address = formattedAddress;
          resolve(locaInfo)
        } else if (status === "error") {
          reject(result)
        }
      });
    })
  })
}

export default getPosition;